package cn.cosmosx.base.generator.excel;

import cn.cosmosx.base.exception.PlatformException;
import cn.cosmosx.base.generator.excel.model.Model;
import cn.cosmosx.base.generator.excel.model.ModelProperty;
import cn.cosmosx.base.generator.excel.param.EntityModelParam;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;

/**
 * 基于Excel模板代码生成服务
 */
@Component
public class AutoExcelCodeGenerator {

    /**
     * 基于Excel生成Java bean
     *
     * @param excelFileStream - Excel
     * @param param           - 参数
     */
    public void generate(InputStream excelFileStream, EntityModelParam param) throws IOException, TemplateException {
        List<ModelProperty> properties = ExcelHeadRowToPropertiesGenerator
                .generate(excelFileStream, param.getSheetNo(), param.getHeadNums(), param.getEndColumnIndex());
        if (properties.isEmpty()) {
            throw new PlatformException("无数据");
        }
        Model model = Model.builder()
                .packageName(param.getPackageName())
                .entityName(param.getEntityName())
                .entityDesc(param.getEntityDesc())
                .tableName(param.getTableName())
                .tablePrefix(param.getTablePrefix())
                .props(properties)
                .build();

        Template modelTemplate = cfg.getTemplate("entity_excel.java.ftl");
        File file = new File("d:/");
        if (!file.exists() && file.mkdirs()) ;
        String name = modelTemplate.getName();
        name = name.substring(0, name.lastIndexOf('.'));
        String suffix = name.substring(name.lastIndexOf('.'));
        String fileName = file.getAbsolutePath() + "/" + model.getEntityName() + suffix;
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)));
        modelTemplate.process(model, out);
        out.flush();
        out.close();
    }

    static Configuration cfg;

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_31);
        cfg.setTemplateLoader(new ClassTemplateLoader(AutoExcelCodeGenerator.class, "/template"));
        cfg.setDefaultEncoding("UTF-8");
    }
}
